package com.swotplus.admin.web.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.swotplus.framework.web.BaseController;
import com.swotplus.admin.web.wrapper.EleTreeWrapper;
import com.swotplus.common.annotation.Log;
import com.swotplus.common.constant.UserConstants;
import com.swotplus.common.core.AjaxResult;
import com.swotplus.common.enums.BusinessType;
import com.swotplus.common.utils.StringUtils;
import com.swotplus.framework.shiro.ShiroUtils;
import com.swotplus.system.sys.entity.SysMenu;
import com.swotplus.system.sys.entity.SysRole;
import com.swotplus.system.sys.entity.SysRoleMenu;
import com.swotplus.system.sys.entity.SysUser;
import com.swotplus.system.sys.service.SysMenuService;
import com.swotplus.system.sys.service.SysRoleMenuService;
import com.swotplus.system.sys.service.SysRoleService;
import com.swotplus.system.sys.service.SysUserRoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜单信息
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController
{
    private String prefix = "system/menu";

    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    private SysUserRoleService sysUserRoleService;

    @RequiresPermissions("system:menu:view")
    @RequestMapping()
    public String menu()
    {
        return prefix + "/list";
    }



    @RequiresPermissions("system:menu:list")
    @RequestMapping("/listData")
    @ResponseBody
    public Map listTreeGridData(SysMenu menu)
    {
        Map retMap = new HashMap();
        QueryWrapper<SysMenu> sysMenuQueryWrapper=new QueryWrapper<>();

        if(StringUtils.isNotBlank(menu.getMenuName())){
          String menuname=menu.getMenuName().replace(",","");
          if(StringUtils.isNotBlank(menuname)){
              sysMenuQueryWrapper.eq("menu_name",menuname);
          }
        }
        List<SysMenu> menuList = sysMenuService.list(sysMenuQueryWrapper);
        retMap.put("msg","success");
        retMap.put("code",0);
        retMap.put("data",menuList);
        retMap.put("count",menuList!=null?menuList.size():0);
        retMap.put("is",true);
        retMap.put("tip","操作成功");
        return retMap;
    }

    /**
     * 删除菜单
     */
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @RequiresPermissions("system:menu:remove")
    @RequestMapping("/remove/{menuId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("menuId") String menuId)
    {
        QueryWrapper<SysMenu> sysMenuQueryWrapper=new QueryWrapper<>();
        sysMenuQueryWrapper.eq("parent_id",menuId);

        QueryWrapper<SysRoleMenu> sysRoleMenuQueryWrapper=new QueryWrapper<>();
        sysRoleMenuQueryWrapper.eq("menu_id",menuId);
        if ( sysMenuService.count(sysMenuQueryWrapper) > 0)
        {
            return AjaxResult.warn("存在子菜单,不允许删除");
        }
        if (sysRoleMenuService.count(sysRoleMenuQueryWrapper) > 0)
        {
            return AjaxResult.warn("菜单已分配,不允许删除");
        }
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(sysMenuService.removeById(menuId));
    }

    /**
     * 新增
     */
    @RequestMapping("/add/{parentId}")
    public String add(@PathVariable("parentId") String parentId, ModelMap mmap)
    {
        SysMenu menu = null;
        if (!parentId.equals("0"))
        {
            menu = sysMenuService.getById(parentId);
        }
        else
        {
            menu = new SysMenu();
            menu.setId(0);
            menu.setMenuType("D");
            //menu.setMenuName("主目录");
        }
        mmap.put("menu", menu);
        return prefix + "/add";
    }

    /**
     * 新增保存菜单
     */
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @RequiresPermissions("system:menu:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysMenu menu)
    {
        QueryWrapper<SysMenu> sysMenuQueryWrapper=new QueryWrapper<>();
        sysMenuQueryWrapper.eq("menu_name",menu.getMenuName());
        if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(sysMenuService.count(sysMenuQueryWrapper)))
        {
            return error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        menu.setCreateBy(ShiroUtils.getLoginName());
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(sysMenuService.save(menu));
    }

    /**
     * 修改菜单
     */
    @RequestMapping("/edit/{menuId}")
    public String edit(@PathVariable("menuId") String menuId, ModelMap mmap)
    {
        mmap.put("menu", sysMenuService.getById(menuId));
        return prefix + "/edit";
    }

    /**
     * 修改保存菜单
     */
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:menu:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysMenu menu)
    {
        QueryWrapper<SysMenu> queryNameWrapper=new QueryWrapper<>();
        queryNameWrapper.eq("menu_name",menu.getMenuName());
        if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(sysMenuService.count(queryNameWrapper)))
        {
            return error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        menu.setUpdateBy(ShiroUtils.getLoginName());
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(sysMenuService.updateById(menu));
    }

    /**
     * 选择菜单图标
     */
    @RequestMapping("/icon")
    public String icon()
    {
        return prefix + "/icon";
    }

    /**
     * 校验菜单名称
     */
    @PostMapping("/checkMenuNameUnique")
    @ResponseBody
    public String checkMenuNameUnique(SysMenu menu)
    {
        QueryWrapper<SysMenu> queryNameWrapper=new QueryWrapper<>();
        queryNameWrapper.eq("menu_name",menu.getMenuName());
        if (sysMenuService.count(queryNameWrapper)>0)
        {
            return UserConstants.MENU_NAME_NOT_UNIQUE;
        }
        return  UserConstants.MENU_NAME_UNIQUE;
    }

    /**
     * 加载角色菜单列表树
     */
    @GetMapping("/roleMenuTreeData")
    @ResponseBody
    public Map roleMenuTreeData(String id)
    {
        Map retMap = new HashMap();
        List<Map<String, Object>> tree = sysMenuService.roleMenuTreeData(id);
        tree = EleTreeWrapper.getInstance().getTree(tree,"pId","id");
        retMap.put("code",0);
        retMap.put("data",tree);
        return retMap;
    }




    /**
     * 加载所有菜单列表树
     */
    @GetMapping("/menuTreeData")
    @ResponseBody
    public List<Map<String, Object>> menuTreeData()
    {
        List<Map<String, Object>>  ztrees = sysMenuService.menuTreeData();
        return ztrees;
    }

    /**
     * 选择菜单树
     */
    @GetMapping("/selectMenuTree/{menuId}")
    public String selectMenuTree(@PathVariable("menuId") String menuId, ModelMap mmap)
    {
        mmap.put("menu", sysMenuService.selectMenuById(menuId));
        return prefix + "/tree";
    }
}